var aspectRatio;

// Add the slider into the player
function load_slider(jsonObj) {
	
	aspectRatio = Math.round(jsonObj.widthVideo / jsonObj.heightVideo * 100) / 100; // A/R of the video
	
    // Create the slider into the player (hidden by default)
	jcoverflip = generate_slider(jsonObj);
	
	var refVideo = jsonObj.referenceVideo;
	var nameVideo = jsonObj.nameVideo;

	// Add informations about the video upside the player (if availables)
	if((refVideo != '') && (typeof refVideo != 'undefined')) {
		$('#refVideo').html('<b><u>Video Ref :</u></b> ' + refVideo);
	} else {
		$('#refVideo').html('');
	}
	
	if((nameVideo != '') && (typeof nameVideo != 'undefined')) {
		$('#nameVideo').html('<b><u>Video Name :</u></b> ' + nameVideo);
	} else {
		$('#nameVideo').html('');
	}
	
	// Fill the timestampArray with the timestamps of all the keyframes
	timestampArray = [];
	$.each(jsonObj.listKeyFrames, function (key, keyFrame) {
		timestampArray.push(mejs.Utility.timeCodeToSeconds(keyFrame.timestamp));
    });
	
/*************mousewheel plugin****************/
	//Go to the previous or next slide on mousewheel
	$(jcoverflip).mousewheel(function(event, delta) {
		
		mediaElementJS.pause();
		
		setTimeout(function() {  
			if (delta < 0) {
				slider_next();
			} else {
				slider_previous();
			}
			
		}, 0);
		
		return false; // To not scroll the page at the same time (default action of the navigator)
	});
	
	// Video must be paused before the image is clicked
	$(".ui-jcoverflip--item img").mousedown(function() {
		mediaElementJS.pause();
	});
	
	// Attach an event to each image of the slider. When the image is clicked, ajax call the corresponding menu is loaded
	$(".ui-jcoverflip--item img").click(function() {

		// Get the source of the image
		var srcKeyFrame = $(this).attr('src');
		var imgIndex = $(this).attr('data-imgindex');
		//alert("src: " + srcKeyFrame);

		var ressourceURL = $('#ressourceURL').attr("value");
		
		//alert(srcKeyFrame); //image
		//alert(ressourceURL);
		//alert(mediaElementJS.src); //video en cours
		
		update_node_selected(imgIndex);
		clearTable();

		$.ajax({
			type : "GET",
			url : ressourceURL,
			data : {
				"reqType" : "getJsonMenu",
				"src" : mediaElementJS.src,
				"srcKeyFrame" : srcKeyFrame
			},
			dataType : "json",
			success : function(jsonMenu) {	
				if((jsonMenu.menus != '') && (typeof jsonMenu.menus != 'undefined')) {
					var videoSrc = jsonMenu.menus[0].cluster[0].src;
					var lastIndex = videoSrc.lastIndexOf("/"); 
					var srcRoot = videoSrc.substring(0, lastIndex+1);
					getMetadonee(srcRoot);
				}
				
				generate_menu(jsonMenu);
			}
		});
	});

};

// Create the slider and put it into the player
function generate_slider(jsonObj) {

    // Video settings
    var playerHeight = $('#videoPlayer').attr('height').replace('px', ''); //Height of the video player
    var centerPicHeight = playerHeight * 1/3; // Height of the center picture
    var arrowHeight = Math.min(55, centerPicHeight*0.5); // The height of the laterals arrow depends of the height of the center picture
    
    var optionParams =
    {
        playerWidth : $('#videoPlayer').attr('width').replace('px', ''), 
        centerPicHeight : playerHeight * 1/3, // Height of the center picture
        sliderBottom : $('#mep_0 .mejs-controls').css('height').replace('px', ''), // Height of the controls (to put the slider upside)
        arrowHeight: arrowHeight,
        arrowWidth: arrowHeight*30/55 // The width of the laterals arrows
    };
    
    
    // Generate the template of the slider and put it inside the player
    var template = generate_template(jsonObj, optionParams).insertBefore($('#mep_0 .mejs-controls'));
    
    // Transform the #flip item into the final slider, with some options
    create_jcoverflip();

    return template;
}

// Instanciate the jcoverflip slider from the template previously created
function create_jcoverflip() {
	
	// If the slider is hidden, it must be displayed to be rebuilt
	var hidden = false; 
	if($(jcoverflip).is(':hidden')) {
		hidden = true;
		$(jcoverflip).show();
	}
	
	var current = $("#flip").jcoverflip('current'); // Get the current slide to select it when the slider is rebuilt
	
	$("#flip").jcoverflip("destroy");
	
	var playerHeight = $('#videoPlayer').attr('height').replace('px', ''); //Height of the video player
	var centerPicHeight = playerHeight * 1/3; // Height of the center picture
	var ratioOtherPic = 0.75; //The size ration for the others pictures
	var centerPicWidth = centerPicHeight * aspectRatio; // Width of the center picture
    var othersPicWidth = centerPicWidth * ratioOtherPic; // Width of the others pictures
    var centerPicPos = centerPicWidth/2; //Position param to place the center picture
    var spaceRightCenterLeft = 8; //Space between before pictures and center, and after pictures and center.
    var spaceOther = 3; // Spaces between others pictures/frames
    var othersPicHeight = centerPicHeight * ratioOtherPic; // Height of the others pictures
    var bottomOther = (centerPicHeight - othersPicHeight) * 0.5; //The bottom of the others pictures
    
	$( '#flip' ).jcoverflip({
      	time: 250,
      	current: current,
      	beforeCss: function( el, container, offset ){
      		return [
      			$.jcoverflip.animationElement( el, { left: ( container.width( )/2 - (centerPicWidth / 2 + othersPicWidth + spaceRightCenterLeft) - (othersPicWidth + spaceOther)*offset  )+'px', bottom: bottomOther+'px' }, { } ),
      			$.jcoverflip.animationElement( el.find( 'img' ), { opacity: 1, width: othersPicWidth +'px', height: othersPicHeight + 'px' }, {} )
      		];
      	},
      	afterCss: function( el, container, offset ){
      		return [
      			$.jcoverflip.animationElement( el, { left: ( container.width( )/2 + (centerPicWidth / 2 + spaceRightCenterLeft) + (othersPicWidth + spaceOther)*offset  )+'px', bottom: bottomOther+'px' }, { } ),
      			$.jcoverflip.animationElement( el.find( 'img' ), { opacity: 1, width: othersPicWidth +'px', height: othersPicHeight + 'px' }, {} )
      		];
      	},
      	currentCss: function( el, container ){
      		return [
      			$.jcoverflip.animationElement( el, { left: ( container.width( )/2 - centerPicPos )+'px', bottom: 0 }, { } ),
      			$.jcoverflip.animationElement( el.find( 'img' ), {opacity: 1.0, width: centerPicWidth+'px', height: centerPicHeight + 'px' }, { } )
      		];
      	}
      });

	if(hidden) {
		$(jcoverflip).hide();
	}
}

// Generate the template of the slider
function generate_template (jsonObj, options) {

    var defaultParams =
    {
       borderContainerT : 2, 
       playerWidth : 640,
       centerPicWidth : 200,
       centerPicHeight : 150,
       sliderBottom : 30,
       arrowHeight: 55,
       arrowWidth: 30
    };

    var param = $.extend(defaultParams, options); 

    // If there is already a slider, it is removed to build the new one
    $('#slider-wrapper').remove();
    
    // You can move inline styles (except 'top', 'left', 'width' and 'height') to css file or css block.
    var wrapper = $('<div id="slider-wrapper" style="width: ' + param.playerWidth + 'px; bottom: ' + param.sliderBottom + 'px;"></div>');
    
    var container = $('<div class="jcoverflip-container" style="height: ' + (param.centerPicHeight + 2 * param.borderContainerT) + 'px;"></div>');

				    // Close-button that hide the slider
				    $('<div id="close-slider" title="Close" ></div>').appendTo(container)
				     .click(function() {
				    	 jcoverflip.fadeOut();
			             jcoverflipButton.toggleClass('slider-button-on slider-button-off');
				     });

        // Arrow left
                    $('<span class="jcoverflipArrowL" style="width: ' + param.arrowWidth + 'px; height: ' + param.arrowHeight + 'px; top: ' + ((param.centerPicHeight+4)-param.arrowHeight)/2 + 'px;"></span>').appendTo(container)
                     .click(function() {
                    	 slider_previous();
                     }).mousedown(function() {
                 		mediaElementJS.pause();
                 	});
                    
        // Arrow Right
                    $('<span class="jcoverflipArrowR" style="width: ' + param.arrowWidth + 'px; height: ' + param.arrowHeight + 'px; top: ' + ((param.centerPicHeight+4)-param.arrowHeight)/2 + 'px;"></span>').appendTo(container)
                    .click(function() {
                    	slider_next();
                    }).mousedown(function() {
                		mediaElementJS.pause();
                	});

        // Slides
        var flip_ = '<ul id="flip" class="ui-jcoverflip" style="height: ' + (param.centerPicHeight + 2 * param.borderContainerT) + 'px;">' ;
                    
                    $.each(jsonObj.listKeyFrames, function (key, slide) {
                    	flip_ += ('<li class="ui-jcoverflip--item" style="left: -115px; bottom: 20px;">'
                                        + '<img data-imgindex="' + slide.idKeyFrame + '" src="'+ slide.src +'">'
                                + '</li>');
                    });
                    
            flip_ += '</ul>';
            
            flip = $(flip_);
                   $(flip).appendTo(container);
                   
            container.appendTo(wrapper);
            
    return wrapper;
}

//Select the next slide
function slider_next() {
	$(flip).jcoverflip('next', '1', false);
}

// Select the previous slide
function slider_previous() {
	$(flip).jcoverflip('previous', '1', false);
}